﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.Common;
using NetCoreCMS.Models;

namespace NetCoreCMS.Web.Areas.WebApi.Controllers
{
    public class UploadFileController : UserController
    {
        private Sysconfig sysConfig;
        // POST: api
        [HttpPost]
        public IActionResult Post()
        {
            sysConfig = Common.XMLConfig.Sysconfig.loadConfig(_env.ContentRootPath);
            string _delfile = CMSRequest.GetQueryString("DelFilePath", HttpContext); //要删除的文件
            string fileName = CMSRequest.GetQueryString("name", HttpContext); //文件名
            var files = Request.Form.Files[0];
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = ContentDispositionHeaderValue
                                .Parse(files.ContentDisposition)
                                .FileName
                                .Trim('"');
            }
            byte[] byteData = FileHelper.ConvertStreamToByteBuffer(files.OpenReadStream()); //获取文件流
            bool _iswater = false; //默认不打水印
            bool _isthumbnail = false; //默认不生成缩略图

            if (Request.Query["IsWater"] == "1")
            {
                _iswater = true;
            }
            //if (Request.Query["IsThumbnail"] == "1")
            //{
                _isthumbnail = true;
            //}
            if (byteData.Length == 0)
            {
                return Content("{\"status\": 0, \"msg\": \"请选择要上传文件！\"}");
            }            
            UpLoad upLoad = new UpLoad(_env.WebRootPath, sysConfig);
            string msg = upLoad.FileSaveAs(byteData, fileName, _isthumbnail, _iswater);
            //删除已存在的旧文件
            if (!string.IsNullOrEmpty(_delfile))
            {
                upLoad.DeleteFile(_delfile.Replace(sysConfig.weburl,""));
            }
            //返回成功信息
            return Content(msg);
        }
    }
}